package com.example.caloriedaily

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ContextMenu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main2.*

class Main2Activity : AppCompatActivity() {
    lateinit var adapter: ArrayAdapter<Note>
    lateinit var dba: DBAccessor  //数据访问对象

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        dba = DBAccessor.getInstance(this)  //获取数据访问对象
        adapter = ArrayAdapter<Note>(
            this,
            android.R.layout.simple_list_item_1, Note.notes
        )
        records.adapter = adapter  //ListView适配器
        registerForContextMenu(records)  //在ListView上注册上下文菜单
    }

    fun add(view: View) {
        val intent = Intent(this, Main3Activity::class.java)
        startActivity(intent)
    }

    //加载数据
    private fun reloadNotes() {
        if (Note.notes.size > 0)
            Note.notes.clear()
        dba.getNotes(Note.notes)
    }

    override fun onResume() {
        super.onResume()
        reloadNotes()
        adapter.notifyDataSetChanged()  //基于适配器更新界面显示
    }

    override fun onCreateContextMenu(
        menu: ContextMenu, v: View,
        menuInfo: ContextMenu.ContextMenuInfo
    ) {
        super.onCreateContextMenu(menu, v, menuInfo)
        menuInflater.inflate(R.menu.context_menu, menu)  //加载上下文菜单
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        val id = item!!.itemId
        if (id == R.id.action_remove) {  //上下文菜单功能
            val info = item.menuInfo as AdapterView.AdapterContextMenuInfo
            val iid = info.id
            val i = Note.notes.get(iid.toInt()).nid
            dba.removeNote(i)  //删除数据
            reloadNotes()
            adapter.notifyDataSetChanged()  //更新界面显示
        }
        return super.onContextItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        dba.closeDB()  //关闭数据库对象
    }

}
